#include <stdio.h>
#include <stdlib.h>
#include "bplustree.h"
#include <string.h>
bptree_node* d_insert(bptree_node* node, int key, int value)
{
    printf("insert key %d insert value %d\n",key,value);
    return insert(node,key,value);
}

void print_bptree(bptree_node* root)
{
    file_record* file;
    int i ;
    if (root->isLeaf == BPLUS_TREE_LEAF) {
        
        for (i = 0;i <= root->num_keys;++i) {
            file = root->pointers[i];
            printf("%d ",file->value);
        }
        printf("\n");
        return  ;
    }
    else {
        for (i = 0;i <= root->num_keys;++i) {
            print_bptree(root->pointers[i]);
        }
    }
}
void d_search(bptree_node* root, int key)
{
    file_record* file = search(root, key);
    if(file == NULL) {
        printf("NO result for %d\n",key);
    }
    else
        printf("search result: %d\n",file->value);
}

void
print_isleaf(bptree_node* node)
{
    if (node->isLeaf == BPLUS_TREE_LEAF)
        printf("LEAF\n");
    else
        printf("NOT Leaf\n");
}
void
print_leaf(bptree_node* leaf)
{
    int i;
    for(i = 0;i < leaf->num_keys;++i)
        printf("%d ",leaf->key[i]);
    puts("");
}
int main(int argc,char **argv)
{
    bptree_node* root = NULL;
    int i, search_test,insert_test;
    search_test  = 1 << 10;
    insert_test = 1 << 10;
    for (i = 1;i <= insert_test;++i) {
        root = d_insert(root,i,i);
    }
    for (i = 1;i <= search_test;++i) {
        d_search(root,i);
    }
    puts("");
    printf("%s\n","请输入操作选项 insert search delete update 输入q退出");
    char ch[5];
    scanf("%s",&ch);
    while (ch[0]!='q') {
        if (strstr(ch,"insert")!=NULL) {
            int k,v;
            printf("%s\n","请输入要插入的数值:k v");
            scanf("%d %d",&k,&v);
            d_insert(root,k,v);
        }
        if (strstr(ch,"search")!=NULL) {
            int k;
            printf("%s\n","请输入索引:k");
            scanf("%d",&k);
            d_search(root,k);
        }
        if (strstr(ch,"delete")!=NULL) {
            int k;
            printf("%s\n","请输入删除的索引:k");
            scanf("%d",&k);
            delete_bptree_node(root,k);
        }
        if (strstr(ch,"update")!=NULL) {
            int k,v;
            printf("%s\n","请输入更新的索引和值:k v");
            scanf("%d %d",&k,&v);
            if (update(root,k,v)) {
                printf("%s\n","更新成功");
            }else{
                printf("%s\n","更新失败,请确认插入结点是否存在");
            }
        }

    scanf("%s",&ch);
    }
    return 0;
}
